package Task04_03;

/*
作业3

火车买票案例 (两种实现方式) : 共100张票,三个线程一起卖票,不允许出现出现负票和多卖的现象  (描述设置锁的时候要注意的事项:(Thread 和Runnable)
 */
public class Sell_01 implements Runnable{
    private int NV ; //描述火车票的票数
    public Sell_01(){
    }
    public Sell_01(int NV) {
        if (NV > 0) {
            this.NV = NV;
        }else
            this.NV = -1;  //此处对初始化的车票数量做判断，如果小于等于0，则返回-1，代表不合理
    }

    public int getNV() {
        return NV;
    }

    public void setNV(int NV) {
        this.NV = NV;
    }

    @Override
    public  synchronized void run() {
//        String LockName = Thread.currentThread().getName();
//        System.out.println(LockName);
        //synchronized (this) {
            //加了 synchronized 关键字代表多个线程中只有一个线程能调用run()方法
            int temp = getNV();
            if (temp < 0) {
                System.out.println("请输入正确的出票数！");
            }
            while (temp > 0){
                System.out.println("剩余票数为：" + temp +"  正在出票...");
                temp -= 1;
                if (temp == 0) {
                    System.out.println("车票已售完！");
                    setNV(temp);
                    break;
                }
            }
       // }
    }

    public static void main(String[] args) {
        Sell_01 sr = new Sell_01(100);
        Thread t1 = new Thread(sr);
        Thread t2 = new Thread(sr);
        Thread t3 = new Thread(sr);
        t2.start();
        t1.start();
        t3.start();

        try {
            t3.join();
            t2.join();
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
